package itcast.dao.impl;

import itcast.dao.BuildDao;
import itcast.domain.Build;

import itcast.domain.Buildmanager;
import itcast.util.JDBCUtils;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class BuildDaoImpl implements BuildDao {
    /**
     * 申明JdbcTemplate类,出入连接池
     */
    private JdbcTemplate template=new JdbcTemplate(JDBCUtils.getDataSource());

    @Override
    public List<Build> findAll() {
        //查找楼宇信息
        //使用jdbc操作数据库
        //1.定义sql
        String sql="select * from build";
        //query返回list集合，BeanPropertyRowMapper指定字节码
        List<Build> builds=template.query(sql,new BeanPropertyRowMapper<Build>(Build.class));

        return builds;
    }
    //添加楼宇数据到数据库


    @Override
    public void add(Build build) {
        //1.定义sql语句
        String sql="insert into build values(null,?,?)";
        //2.执行sql
        template.update(sql,build.getBuild_name(), build.getBuild_introduction());
    }

    //根据id查找数据库信息
    @Override
    public Build findById(int id) {
        //1.定义sql语句
        String sql="select * from build where Build_ID=?";
        return template.queryForObject(sql,new BeanPropertyRowMapper<Build>(Build.class),id);

    }

    //修改数据库数据
    @Override
    public void update(Build build) {
        //1.定义sql语句
        String sql="update build set Build_Name=?, Build_Introduction=? where  Build_ID=?";
        //执行sql语句
        template.update(sql,build.getBuild_name(),build.getBuild_introduction(),build.getBuild_id());
    }

    //删除数据库数据

    @Override
    public void delete(int id) {
        //1.定义sql
        String sql="delete from build where Build_ID=?";
        //2.执行sql
        template.update(sql,id);
    }
    //条件查询数据库

    @Override
    public List<Build> findByDate(Map<String, String[]> condition) {
        //1.定义模板初始化sql
        String sql="select * from build where 1=1";
        StringBuilder sb=new StringBuilder(sql);
        //2.遍历map中value是否有值
        Set<String> keySet =condition.keySet();
        //定义参数集合
        List<Object> params=new ArrayList<Object>();
        for(String key :keySet){
            //获取value
            String value=condition.get(key)[0];
            //判断value是否有值
            if(value!=null && !"".equals(value)){
                sb.append(" and "+key+" like ? ");
                params.add("%"+value+"%");//条件的值
            }
        }
        System.out.println(sb.toString());
        System.out.println(params);
        List<Build> builds=template.query(sb.toString(),new BeanPropertyRowMapper<Build>(Build.class),params.toArray());
        return builds;
    }
}
